home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17202 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  62 lines

  1. Newsgroups: comp.lang.c++
  2. Path: artemis.sto.fdata.se!news
  3. From: Niklas Mellin <niklas.mellin@sto.fdata.se>
  4. Subject: Re: Calling the wrong constructor
  5. Sender: news@artemis.sto.fdata.se (UseNet NetNews)
  6. Message-ID: <3170DEB7.66C6@sto.fdata.se>
  7. Date: Sun, 14 Apr 1996 11:17:11 GMT
  8. Content-Transfer-Encoding: 7bit
  9. Content-Type: text/plain; charset=us-ascii
  10. References: <4kot87$796@earth.njcc.com> <4kpm4c$jfe@nntp1.best.com>
  11. Mime-Version: 1.0
  12. X-Mailer: Mozilla 2.0 (WinNT; I)
  13. Organization: WM-data F÷rsvarsdata AB, Sweden
  14.  
  15. John Lockwood wrote:
  16. > mike@pluto.njcc.com (Michael Hohenshilt) wrote:
  17. > >  This might seem like a basic question, but lets say you something set u
  18. > >like the following:
  19. > >class Parent { Parent() { allocsomething} ~Parent() { deletesomething }... };
  20. > >class Foo : Parent { Foo() { allocsomething } ~Foo() {deletesomething }... };
  21. > >class Contain { Parent *ptr; ... };
  22. > >both parent, and foo allocate memory, and will free it up when being
  23. > >destructed.  Contain just holds a pointer of type Parent, and its
  24. > >constructor takes such a pointer as a parameter.
  25. > >  If I store a pointer of type Foo into contain.ptr and discard that
  26. > >pointer.  Is there any way to have contain (via destructors) free up all
  27. > >memory allocated by Foo and/or Parent?
  28. > >         Mike
  29. > The destructors need to be virtual.
  30. > virtual ~Foo() { { /* ... */ }
  31. > virtual ~Parent() { /* ... */ }
  32.  
  33. Only Parent has to be expicitly declared virtual, declaring derived
  34. classes overloaded functions as virtual when they are already declared
  35. virtual in the base class is optional. A good habit though since it
  36. might make the code clearer.
  37.  
  38. > Then a base class pointer pointing to a derived class will do the
  39. > right thing.  Note that the code as you've written it wouldn't
  40. > do any base class allocation, since you didn't call your parent
  41. > constructor.
  42.  
  43. WRONG WRONG WRONG!!!!
  44.  
  45. When the constructor of a derived class is called it will always
  46. first call the base class constructor. If nothing else is specified
  47. it will use the default constructor, and if there is no default
  48. constructor declared, the compiler will generate one for you.
  49.  
  50. > Bad programmer!  Just for that, no JOLT cola!  ;-)
  51.  
  52. Neither for you! ;-)
  53.  
  54. ---
  55. Niklas Mellin
  56.